package cn.icanci.loopstack.bic.biz.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;

import cn.icanci.loopstack.bic.biz.dts.GraphDtsServiceProxy;
import cn.icanci.loopstack.bic.biz.mapper.SystemMapper;
import cn.icanci.loopstack.bic.biz.service.SystemService;
import cn.icanci.loopstack.bic.common.model.TextValue;
import cn.icanci.loopstack.bic.common.model.base.SystemVO;
import cn.icanci.loopstack.bic.dal.mongo.common.PageList;
import cn.icanci.loopstack.bic.dal.mongo.daointerface.SystemDAO;
import cn.icanci.loopstack.bic.dal.mongo.dateobject.SystemDO;

/**
 * @author icanci
 * @since 1.0 Created in 2023/09/10 15:21
 */
@Service
public class SystemServiceImpl implements SystemService {

    @Resource
    private SystemDAO            systemDAO;
    @Resource
    private SystemMapper         systemMapper;
    @Resource
    private GraphDtsServiceProxy graphDtsServiceProxy;

    @Override
    public List<SystemVO> queryAll() {
        return systemMapper.dos2vos(systemDAO.queryAll());
    }

    @Override
    public void save(SystemVO systemVO) {
        // TODO 日志记录
        if (doInsert(systemVO)) {
            SystemDO insert = systemMapper.vo2do(systemVO);
            systemDAO.insert(insert);
            graphDtsServiceProxy.dtsUnitViewTree(systemMapper.do2vo(insert));
        } else {
            systemDAO.update(systemMapper.vo2do(systemVO));
        }
    }

    @Override
    public SystemVO queryById(String id) {
        return systemMapper.do2vo(systemDAO.queryOneById(id));
    }

    @Override
    public PageList<SystemVO> queryPage(SystemVO systemVO, int pageNum, int pageSize) {
        PageList<SystemDO> pageQuery = systemDAO.pageQuery(systemMapper.vo2do(systemVO), pageNum, pageSize);
        return new PageList<>(systemMapper.dos2vos(pageQuery.getData()), pageQuery.getPaginator());
    }

    @Override
    public List<TextValue> loadSelector() {
        List<SystemVO> systems = queryAll();
        List<TextValue> textValues = Lists.newArrayList();
        for (SystemVO system : systems) {
            String label;
            if (isDeleted(system)) {
                label = String.format(DELETED_FORMAT, system.systemName());
            } else {
                label = String.format(NOT_DELETED_FORMAT, system.systemName());
            }
            String value = system.getUuid();
            textValues.add(new TextValue(label, value));
        }
        return textValues;
    }

    @Override
    public SystemVO queryByName(String name) {
        return systemMapper.do2vo(systemDAO.queryByName(name));
    }

    @Override
    public SystemVO queryByKey(String key) {
        return systemMapper.do2vo(systemDAO.queryByKey(key));
    }

    @Override
    public SystemVO queryByUuid(String systemUuid) {
        return systemMapper.do2vo(systemDAO.queryByUuid(systemUuid));
    }
}
